<template>
  <div class="form-container">
    <h2>MQTT Client</h2>
    <div class="form-group-row">
      <div class="form-group form-group-host">
        <label for="host">Host:</label>
        <input list="hosts" id="host" v-model="host" placeholder="请输入或选择主机地址">
        <datalist id="hosts">
          <option value="111.225.221.132">111.225.221.132</option>
          <option value="192.168.9.39">192.168.9.39</option>
        </datalist>
      </div>
      <div class="form-group form-group-port">
        <label for="port">Port:</label>
        <input type="number" id="port" v-model="port" placeholder="MQTT服务器端口">
      </div>
      <div class="form-group form-group-clientID">
        <label for="clientID">Client ID:</label>
        <input type="text" id="clientID" v-model="clientID" placeholder="客户端ID">
      </div>
      <div class="form-group form-group-username">
        <label for="username">用户名:</label>
        <input type="text" id="username" v-model="username" placeholder="MQTT用户名">
      </div>
      <div class="form-group form-group-password">
        <label for="password">密码:</label>
        <input type="text" id="password" v-model="password" placeholder="MQTT密码">
      </div>
    </div>

    <div class="form-group-row">
      <div class="form-group form-group-topics">
        <label for="topics">topics:</label>
        <input type="text" id="topics" v-model="topics" placeholder="请输入topics">
      </div>
      <div class="form-group form-group-topics">
        <label for="rtuCode">rtuCode:</label>
        <input type="text" id="rtuCode" v-model="rtuCode" placeholder="设备号">
      </div>

    </div>


    <!-- 修改此处，添加 button-row 类 -->
    <div class="form-group button-row">
      <button @click="connect" class="submit-btn">连接</button>
      <button @click="disconnect" class="submit-btn">断开连接</button>
      <button @click="checkConnectionStatus" class="submit-btn">查连接状态</button>
      <button @click="subscribe" class="submit-btn">订阅主题</button>
      <button @click="unSubscribe" class="submit-btn">取消订阅主题</button>
      <button @click="sendMessage" class="submit-btn">Send Message</button>
      <button @click="testConnection" class="submit-btn">测试连接</button>

    </div>
    <div class="result-container">
      <pre>{{ result }}</pre>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'; // 新增生命周期函数
import axios from 'axios';
import SockJS from 'sockjs-client';
import { Client } from '@stomp/stompjs';

const host = ref('111.225.221.132');
const port = ref('8222');
const generateRandomEightDigits = () => {
  return Math.floor(10000000 + Math.random() * 90000000).toString();
};
const clientID = ref(generateRandomEightDigits());
const username = ref('admin');
const password = ref('12345678');
const result = ref('');
const socket = ref(null);
const reconnectAttempts = ref(0); // 新增重连计数器
const maxReconnectAttempts = 5;   // 最大重连次数
const reconnectInterval = 5000;   // 重连间隔(ms)
let reconnectTimer = null;        // 重连定时器

onMounted(() => {
  // initWebSocket();
});

// 新增初始化方法
const initWebSocket = () => {
  socket.value = new WebSocket('ws://192.168.0.109:8081/ws');

  socket.value.onopen = () => {
    console.log('Connected to WebSocket server');
    reconnectAttempts.value = 0; // 重置重连计数器
  };

  socket.value.onmessage = (event) => {
    console.log('Received:', event.data);
    // const newData = JSON.stringify(JSON.parse(event.data), null, 2);
    const newData = event.data;
    result.value = `${new Date().toLocaleString()}:\n${newData}\n${result.value}\n`;
  };

  socket.value.onerror = (error) => {
    console.error('WebSocket error:', error);
  };

  socket.value.onclose = (event) => {
    console.log(`连接关闭，代码: ${event.code}, 原因: ${event.reason}`);
    
    // 非主动关闭时尝试重连
    if (event.code !== 1000 && reconnectAttempts.value < maxReconnectAttempts) {
      reconnectAttempts.value++;
      console.log(`将在 ${reconnectInterval/1000} 秒后尝试第 ${reconnectAttempts.value} 次重连`);
      reconnectTimer = setTimeout(initWebSocket, reconnectInterval);
    }
  };
};

// 修改卸载逻辑
onBeforeUnmount(() => {
  if (socket.value) {
    // 主动关闭时使用正常关闭代码
    if (socket.value.readyState === WebSocket.OPEN) {
      socket.value.close(1000, '组件卸载主动关闭');
    }
    socket.value = null;
  }
  // 清除重连定时器
  if (reconnectTimer) {
    clearTimeout(reconnectTimer);
  }
});

const sendRequest = async (commandType) => {
  try {
    const response = await axios.post('http://192.168.0.109:8081/api/mqtt/connect', {
      clientID: clientID.value,
      username: username.value,
      password: password.value,
      host: host.value,
      port: port.value,
      commandType: commandType
    });
    console.log('返回的消息:', response.data);
    const newData = JSON.stringify(response.data, null, 2);
    result.value = `${new Date().toLocaleString()}:\n${newData}\n${result.value}\n`; // 追加模式
  } catch (error) {
    console.error('请求出错:', error);
    result.value = `请求出错: ${error.message}`;
  }
};

const connect = async () => {
  await sendRequest('connect');
};

const disconnect = async () => {
  await sendRequest('disConnect');
};

const checkConnectionStatus = async () => {
  await sendRequest('isConnected');
};
const topics = ref('$creq/00001234,$crsp/00001234'); // 设置完整默认值
const rtuCode = ref('00001234');

// 公共请求方法
const handleTopicRequest = async (dealType, errorMessage) => {
  try {
    const response = await axios.post('http://192.168.0.109:8081/api/mqtt/deal', {
      dealType,
      topics: topics.value
    });
    const newData = JSON.stringify(response.data, null, 2);
    result.value = `${new Date().toLocaleString()}:\n${newData}\n${result.value}\n`;
  } catch (error) {
    const msg = `${errorMessage}: ${error.message}`;
    result.value = `${new Date().toLocaleString()}:\n${msg}\n${result.value}\n`;
  }
};

const subscribe = async () => {
  await handleTopicRequest('subscribe', '订阅失败');
};

const unSubscribe = async () => {
  await handleTopicRequest('unSubscribe', '取消订阅失败');
};



onMounted(() => {
  socket.value = new WebSocket('ws://192.168.0.109:8081/ws');

  socket.value.onopen = () => {
    console.log('Connected to WebSocket server');
  };

  socket.value.onmessage = (event) => {
    console.log('Received:', event.data);
    // const newData = JSON.stringify(JSON.parse(event.data), null, 2);
    const newData = event.data;
    result.value = `${new Date().toLocaleString()}:\n${newData}\n${result.value}\n`;
  };

  socket.value.onerror = (error) => {
    console.error('WebSocket error:', error);
  };

  socket.value.onclose = () => {
    console.log('Disconnected from WebSocket server');
  };
});

onBeforeUnmount(() => {
  if (socket.value) {
    if (socket.value.readyState === WebSocket.OPEN) {
      socket.value.close();
      console.log('WebSocket连接已主动关闭');
    }
    socket.value = null;
  }
});

const sendMessage = () => {
  if (socket.value.readyState === WebSocket.OPEN) {
    socket.value.send(JSON.stringify({ content: 'Hello, Server!' }));
  } else {
    console.error('WebSocket is not open');
  }
};

const testConnection = () => {
  if (socket.value.readyState === WebSocket.OPEN) {
    const message = {
      type: "command",
      command:"test-connection",
      rtuCode: rtuCode.value
    };
    socket.value.send(JSON.stringify(message));
    console.log('发送测试连接消息:', message);
  } else {
    console.error('WebSocket is not open');
  }
};

</script>

<style scoped>
.form-container {
  padding: 20px;
}

.form-group-row {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 5px;
}

.form-group input {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}



.submit-btn:hover {
  background-color: #0056b3;
}

/* 修改 button-row 类样式 */
.button-row {
  display: flex;
  flex-direction: row;
  /* 强制横向排列 */
  gap: 10px;
  align-items: center;
  /* 垂直居中 */
}

.submit-btn {
  padding: 10px 20px;
  background-color: rgb(76, 126, 76);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  width: auto;
  /* 修改此处，移除固定宽度计算 */
  min-width: 120px;
  /* 添加最小宽度保持按钮统一 */
}

.result-container {
  margin-top: auto;
  /* 自动填充顶部空间 */
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  background-color: #f9f9f9;
  height: 24em;
  /* 高度加倍 */
  width: 100%;
  overflow-y: auto;
}

.form-container {
  padding: 20px;
  min-height: 100vh;
  /* 确保容器有足够的高度空间 */
  display: flex;
  flex-direction: column;
  /* 启用垂直排列 */
}

.result-container pre {
  margin: 0;
  white-space: pre-wrap;
}
</style>